/**
 * Created by cchen on 2015/4/16.
 */
var Users = mongoose.model('user');
var md5 = require('MD5');
var http = require('http');
var toolUtil = require('../common/utils/toolUtil');

exports.getDuibaUrl = function (token, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, "");
        } else {
            /*  宝宝树66小区二次改造    mod   chenf  20170721  start   */
            /*scoreProxy.invoke('getScoreInfoByUid', [token + ''], function (err, result) {
                    if (err) {
                    logger.error(err.message);
                } else {
                    var data = JSON.parse(decodeURIComponent(result));
                    if (data.status != 0) {
                        logger.error('getUserScore----' + data.msg);
                        callback(err, '');
                    } else {
                        var score = data.data.scoreInfo.currentValue;
                        var opt = {};
                        opt.uid = token;
                        opt.credits = score;
                        opt.appKey = duibaAppkey;
                        opt.timestamp = new Date().getTime();
                        opt.appSecret = duibaAppSecret;

                        var arg = ["uid", "credits", "appKey", "timestamp", "appSecret"];
                        arg.sort();

                        var str = "";
                        for (var i = 0; i < arg.length; i++) {
                            str += opt[arg[i]];
                        }

                        var sign = md5(str);

                        var url = 'http://www.duiba.com.cn/autoLogin/autologin?uid=' + token + '&credits=' + score + '&appKey=' + duibaAppkey + '&timestamp=' + opt.timestamp + '&sign=' + sign;
                        logger.info(url);

                        callback(err, url);
                    }
                }
            })*/

            var opt = {};
            opt.uid = token;
            opt.credits = "0";
            opt.appKey = "41sKUDArdECb7iwntFhewrxywLyb";
            opt.timestamp = new Date().getTime();
            opt.redirect = "https://activity.m.duiba.com.cn/newtools/index?id=2339802";
            opt.appSecret = "2XtFatEJhZGGms8gJLhWoTWikqbR";
            var arg = ["uid", "credits", "appKey", "timestamp", "redirect", "appSecret"];
            //var arg = ["appKey", "timestamp", "redirect"];
            arg.sort();

            var str = "";
            for (var i = 0; i < arg.length; i++) {
                str += opt[arg[i]];
            }
            var sign = md5(str);

            /*var url = 'http://www.duiba.com.cn/autoLogin/autologin?uid=' + token + '&credits=' + score + '&appKey=' + duibaAppkey + '&timestamp=' + opt.timestamp + '&sign=' + sign;*/
            /*var url = 'https://activity.m.duiba.com.cn/newtools/preview?id=2339802&type=dev&dbnewopen&from=login&spm=15556.1.1.1'*/

            var url = 'http://www.duiba.com.cn/autoLogin/autologin?uid=' + token + '&appKey=' + opt.appKey + '&timestamp='+ opt.timestamp + '&credits=' + opt.credits + '&sign=' + sign + '&redirect='+ opt.redirect;
            logger.info(url);
            callback(err, url);
            /*  宝宝树66小区二次改造    mod   chenf  20170721  end   */
        }
    });

};

exports.dedScore = function (input, callback) {
    toolUtil.getUserByToken(input.uid, function (err, user) {
        if (err) {
            logger.error('Exception happened when dedScore ...!' + err.message);
            var back = {
                status: "fail",
                errorMessage: "系统错误，请联系小6客服",
                bizId: 0,
                credits: input.credits
            };

            callback(err, back);
        } else {
            exchangeProxy.invoke('exchangeDuibaProduct', [input], function (err, result) {
                logger.info(result);
                if (err) {
                    logger.error('Exception happened when dedScore ...!' + err.message);

                    var back = {
                        status: "fail",
                        errorMessage: "系统错误，请联系小6客服",
                        bizId: 0,
                        credits: input.credits
                    };

                    callback(err, back);
                } else {

                    var data = JSON.parse(decodeURIComponent(result));

                    if (data.status != 0) {
                        logger.error('dedScore error---' + data.msg);
                        var back = {
                            status: "fail",
                            errorMessage: data.msg,
                            bizId: 0,
                            credits: input.credits
                        };

                        callback(err, back);
                    } else {

                        var back = {
                            status: "ok",
                            bizId: data.data.recordId,
                            credits: data.data.currentValue
                        };

                        //var message = '已收到您的兑换申请，小6将尽快为您兑换，如有疑问，请随时联系小6';
                        //toolUtil.pushCustomerServiceMessage(user, message);

                        callback(err, back);
                    }
                }
            });
        }
    });

};

exports.dedScore = function (input, callback) {
    toolUtil.getUserByToken(input.uid, function (err, user) {
        if (err) {
            logger.error('Exception happened when dedScore ...!' + err.message);
            var back = {
                status: "fail",
                errorMessage: "系统错误，请联系小6客服",
                bizId: 0,
                credits: input.credits
            };

            callback(err, back);
        } else {
            exchangeProxy.invoke('exchangeDuibaProduct', [input], function (err, result) {
                logger.info(result);
                if (err) {
                    logger.error('Exception happened when dedScore ...!' + err.message);

                    var back = {
                        status: "fail",
                        errorMessage: "系统错误，请联系小6客服",
                        bizId: 0,
                        credits: input.credits
                    };

                    callback(err, back);
                } else {

                    var data = JSON.parse(decodeURIComponent(result));

                    if (data.status != 0) {
                        logger.error('dedScore error---' + data.msg);
                        var back = {
                            status: "fail",
                            errorMessage: data.msg,
                            bizId: 0,
                            credits: input.credits
                        };

                        callback(err, back);
                    } else {

                        var back = {
                            status: "ok",
                            bizId: data.data.recordId,
                            credits: data.data.currentValue
                        };

                        //var message = '已收到您的兑换申请，小6将尽快为您兑换，如有疑问，请随时联系小6';
                        //toolUtil.pushCustomerServiceMessage(user, message);

                        callback(err, back);
                    }
                }
            });
        }
    });

};

exports.getDuibaResult = function (input, callback) {
    exchangeProxy.invoke('examineDuibaProduct', [input], function (err, result) {
        callback(err,result)
    });
};

exports.exchangeVirtualProduct = function (input, callback) {
    toolUtil.getUserByToken(input.uid, function (err, user) {
        if (err) {
            logger.error('Exception happened when exchangeVirtualProduct ...!' + err.message);
            var back = {
                status: "fail",
                errorMessage: "系统错误，请联系小6客服",
                supplierBizId: 0,
                credits: input.credits
            };

            callback(err, back);
        } else {
            exchangeProxy.invoke('examineDuibaVirtualProduct', [input], function (err, result) {
                logger.info(result);
                if (err) {
                    logger.error('Exception happened when exchangeVirtualProduct ...!' + err.message);

                    var back = {
                        status: "fail",
                        errorMessage: "系统错误，请联系小6客服",
                        supplierBizId: 0,
                        credits: input.credits
                    };

                    callback(err, back);
                } else {

                    var data = JSON.parse(decodeURIComponent(result));

                    if (data.status != 0) {
                        logger.error('dedScore exchangeVirtualProduct---' + data.msg);
                        var back = {
                            status: "fail",
                            errorMessage: data.msg,
                            supplierBizId: 0,
                            credits: input.credits
                        };

                        callback(err, back);
                    } else {

                        var back = {
                            status: "success",
                            supplierBizId: data.data.recordId,
                            credits: data.data.currentValue
                        };

                        //var message = '已收到您的兑换申请，小6将尽快为您兑换，如有疑问，请随时联系小6';
                        //toolUtil.pushCustomerServiceMessage(user, message);

                        callback(err, back);
                    }
                }
            });
        }
    });

};